# encoding: utf-8
class TransacoesController < ApplicationController

	before_filter :load_transacao, :only => [:edit, :delete, :destroy, :show]

	#
	#
	def pendentes
		filtro_params = params[:filtro]
		@filtro = SearchHelper::Extrato.new(filtro_params)

		if params[:commit]
			@pendentes = Transacao.pendentes(current_usuario, @filtro.periodo)
		end
	end

	#
	#
	def destroy
		if @transacao.destroy
			redirect_to conta_path(@transacao.conta),
				:notice => "#{I18n.t @transacao.class.name, :scope => 'classes'} excluído com sucesso"
		else
			render :delete
		end
	end
	
	#
	#
	def extrato
		extrato_params = params[:filtro]
		@filtro = SearchHelper::Extrato.new(extrato_params)

		if params[:commit]
			@extrato = Transacao.extrato(@filtro.conta_id,
				@filtro.periodo, @filtro.nao_quitadas?, @filtro.omitir_transferencias?)
		end
	end
	
	#
	#
	def load_conta(clazz)
		conta_id = case params[:action]
			when "new" then params[:conta_id]
			when "create" then params[clazz.model_name.downcase][:conta_id]
			when "update" then params[clazz.model_name.downcase][:conta_id]
			else nil
		end

		unless empty?(conta_id)
			begin
				@conta = Conta.find(conta_id)

				unless belongs_to_current_usuario?(@conta)
					flash[:alert] = "Conta inválida"
					redirect_to contas_path and return
				end
			rescue ActiveRecord::RecordNotFound
				flash[:alert] = "Conta inválida"
				redirect_to contas_path and return
			end
		end
	end
	
	private
	
	#
	#
	def load_transacao
		begin
			@transacao = Transacao.find(params[:id])
		rescue ActiveRecord::RecordNotFound
			redirect_to contas_path, "Operação inválida"
		end

		unless belongs_to_current_usuario?(@transacao.conta)
			redirect_to contas_path, "Operação inválida"
		end
	end
end
